<?php

/**
 * User Controller.
 *
 * Helpful methods to make Controller.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       User.Controller
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('UserAppController', 'User.Controller');

/**
 * Autocomple in PHP's IDE solution
 * 
 * @property User $User
 * 
 */
Class RolesController extends UserAppController {

    /**
     * Use model class
     *
     * @var array
     */
    public $uses = array('User.Role');

    /**
     * Called after the controller action.  
     *
     * @return void
     */
    public function beforeRender() {
        parent::beforeRender();
        if (in_array($this->request['action'], array('admin_add', 'admin_edit'))) {
            $layouts = $this->Dashboard->get($this->Role, 'layouts');
            if (empty($layouts)) {
                $layouts = array(null, array_keys($this->Role->schema()));
            }
            $this->set('_layouts', $layouts);
        }
    }
    public function beforeFilter(){
        parent::beforeFilter();
        if (in_array($this->request['action'], array('admin_add','admin_edit'))) {
            $this->Components->disable('Security');
        }
    }
    /**
     * Management data
     *
     * @return void
     */
    public function admin_index() {
        $_paginate = array(
            'order' => array('rght' => 'asc'),
            'fields' => array('id')
        );
        $this->Dashboard->parseRequest($this->Role, $_paginate, array('name'));
        $roles = $this->paginate();

        $this->Dashboard->translateMaps($this->Role, $roles);
        $this->Dashboard->toolbar(__d('system', 'Roles management'), array(
            'add' => array('action' => 'add', 'text' => __d('system', 'Add')),
            'edit' => array('action' => 'edit', 'text' => __d('system', 'Edit')),
            'remove' => array('action' => 'removes', 'text' => __d('system', 'Delete'))
        ));
        if ($this->request->is('post')) {
            $data = array_merge(array('task' => '', 'id' => array(null)), $this->request->data['Paginate']);
            switch (strtolower($data['task'])) {
                case 'add': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0]));
                    }
                case 'copy': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0]));
                    }
                case 'edit': {
                        $this->Dashboard->redirect(array('action' => 'edit', $data['id'][0]));
                    }
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $data['id'])));
                    }
            }
        }
        $roleMap = $this->Role->roleMap();
        $this->set(compact('roles', 'roleMap'));
    }

    /**
     * Add data
     *
     * @return void
     */
    public function admin_add($id = null, $parent = null) {
        $this->loadModel('Node.NodeType');
        $this->loadModel('User.RoleNodeType');
        $this->Dashboard->exists($this->Role, $id, false);
        $this->Dashboard->toolbar(__d('system', 'Add new Role'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'next' => array('action' => 'save', 'text' => __d('system', 'Save & Add New')),
            'cancel' => __d('system', 'Cancel')
        ));                      
        if ($this->request->is('post')) {
            $data = $this->request->data;
            $this->Role->create();
            $task = strtolower($this->request->data['Paginate']['task']);
            if (empty($task) || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            }                                               
            if ($this->Role->save($this->request->data)) {
                $role_id = intval($this->Role->id);
                $this->RoleNodeType->deleteAll(array('RoleNodeType.role_id'=>$role_id));
                if(!empty($data['Role']['NodeType'])){                    
                    $arr_node = $data['Role']['NodeType'];                     
                    $data['RoleNodeType']['role_id'] = $role_id; 
                    foreach($arr_node as $key=>$value){
                       $data['RoleNodeType']['node_type_id'] = $value; 
                       $this->RoleNodeType->create();
                       $this->RoleNodeType->save($data['RoleNodeType']); 
                    }    
                }
                $this->setFlash(__d('system', 'The %s has been saved', __d('system', 'Role')), 'success');
                switch ($task) {
                    case 'next': {
                            $this->redirect($this->request->here(false));
                        }
                    case 'apply': {
                            $this->Dashboard->redirect(array('action' => 'edit', $this->Role->getInsertID()), false, true);
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be saved. Please, try again.', __d('system', 'Role')), 'error');
            }
        } elseif ($id) {
            $this->request->data = $this->Role->read(array('recursive' => -1), $id);            
        }        
        $listSubSite = Configure::read('App.themes.listSubSite'); $listSubSite = Configure::read('App.themes.listSubSite'); 
        $first_subsite = null;
        if(!empty($listSubSite)){
            $first_subsite = key($listSubSite);              
        }
        $rolesNodeType = null;
        $rolesNodeType = $this->NodeType->find('all',array(
            'conditions'=>array('NodeType.sub_site'=>$first_subsite,'NodeType.enabled'=>1),
            'fields'=>array('NodeType.id','NodeType.name'),
            'recursive'=>-1
        ));                  
        $this->set(compact('listSubSite'));
        $roleMap = $this->Role->roleMap();
        $this->set(compact('roleMap', 'id','rolesNodeType'));
    }

    /**
     * Edit data
     *
     * @return void
     */
    public function admin_edit($id = null) {
        $this->Dashboard->exists($this->Role, $id);
        $this->Dashboard->toolbar(__d('system', 'Edit Role #%s', $id), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Delete')),
            'cancel' => __d('system', 'Cancel')
        ));
        $this->loadModel('User.RoleNodeType');
        $this->loadModel('Node.NodeType');
        if ($this->request->is('post')) {
            $data = $this->request->data;            
            $task = strtolower($this->request->data['Paginate']['task']);
            switch ($task) {
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $id)), false, true);
                    }
                case '':
                case 'cancel': {
                        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
                    }
            }
            if ($this->Role->save($this->request->data)) {
                $role_id = intval($this->Role->id);
                $this->RoleNodeType->deleteAll(array('RoleNodeType.role_id'=>$role_id));
                if(!empty($data['Role']['NodeType'])){                                        
                    $arr_node = $data['Role']['NodeType']; 
                    $data['RoleNodeType']['role_id'] = $role_id; 
                    foreach($arr_node as $key=>$value){
                       $data['RoleNodeType']['node_type_id'] = $value; 
                       $this->RoleNodeType->create();
                       $this->RoleNodeType->save($data['RoleNodeType']); 
                    }    
                }
                $this->setFlash(__d('system', 'The %s has been updated', __d('system', 'Role')), 'success');
                switch ($task) {
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be updated. Please, try again.', __d('system', 'User')));
            }
        } else {
            $listSubSite = Configure::read('App.themes.listSubSite');
            $first_subsite = null;
            if(!empty($listSubSite)){
                $first_subsite = key($listSubSite);              
            }
            $rolesNodeType = null;            
            $rolesNodeType = $this->NodeType->find('all',array(
                'conditions'=>array('NodeType.sub_site'=>$first_subsite,'NodeType.enabled'=>1),
                'fields'=>array('NodeType.id','NodeType.name'),
                'recursive'=>-1
            ));             
            $this->request->data = $this->Role->read(array(), $id);
            $this->set(compact('listSubSite'));
        }
        $roleMap = $this->Role->roleMap();
        $this->set(compact('roleMap', 'id','listSubSite','rolesNodeType'));
    }

    /**
     * Delete data
     *
     * @return void
     */
    public function admin_delete() {
        if (empty($this->request->query['keys'])) {
            $this->setFlash(__d('system', 'Select elements should be deleted from the list below!', __d('system', 'Role')));
        } else {
            $complete = 0;
            $message = null;
            $keys = (array) $this->request->query['keys'];
            foreach ($keys as $key) {
                if (!$this->Role->delete($key)) {
                    $message = $this->Role->getMessage();
                    if (!$message) {
                        $message = __d('system', 'Cannot delete row #%s.', $key);
                    }
                    break;
                } else {
                    $complete++;
                }
            }
            if ($message) {
                $message = __d('system', '<br/>The processing has stopped because : <b>%s</b>', $message);
            }
            $this->setFlash(__d('system', 'The %1$s has been deleted %2$s / %3$s rows.', __d('system', 'Role'), $complete, count($keys)) . $message, 'warning');
        }
        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
    }

}

?>
